package com.handersome.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.handersome.dto.ErrorDTO;
import com.handersome.exception.MyException;

/**
 * 全局异常处理器，统一异常处理，而非每个controller中逐一定义
 * @author handersome
 *
 * @version 创建时间：2017年12月1日 下午5:04:13
 */
@ControllerAdvice
public class GlobalExceptionController {
	
	private static final Log log = LogFactory.getLog(GlobalExceptionController.class);

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ErrorDTO error(HttpServletRequest req, Exception e){
		ErrorDTO error = new ErrorDTO();
		error.setCode(1);
		error.setMsg("请求错误");
		error.setUrl(req.getRequestURL().toString());
		return error;
	}
	
	@ExceptionHandler(value = MyException.class)
	public ModelAndView errorPage(HttpServletRequest req, MyException e){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("error-page.ftl");
		log.info("错误页面");
		ErrorDTO error = new ErrorDTO();
		error.setCode(1);
		error.setMsg("请求错误");
		error.setUrl(req.getRequestURL().toString());
		mav.addObject("errorInfo", error);
		return mav;
	}
}
